<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="14">
        <el-card class="category-data-card">
          <template #header>
            <div class="category-header">
              <div class="title">一级分类</div>
              <div class="add-category" @click="openDialog">新增一级分类</div>
            </div>
          </template>

          <el-table
            style="margin-bottom: 20px"
            ref="singleTableRef"
            highlight-current-row
            @current-change="handleCategoryCurrentChange"
            :data="parentArr"
            @selection-change="selectedChange"
          >
            <el-table-column
              type="index"
              header-align="left"
              align="left"
              width="80"
              label="序号"
            >
              <template #default="scope">
                <span>{{ (current - 1) * pageSize + scope.$index + 1 }}</span>
              </template>
            </el-table-column>

            <el-table-column
              align="left"
              label="分类名称"
              prop="name"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              align="left"
              label="创建时间"
              prop="createTime"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              align="center"
              label="操作"
              width="150px"
              style="display: flex; justify-content: center"
            >
              <template v-slot="{ row }" style="display: flex; gap: 10px">
                <div class="cell" style="display: flex">
                  <div
                    class="option"
                    style="
                      flex: 1;
                      text-align: center;
                      cursor: pointer;
                      margin-right: 5px;
                    "
                    @click="editCategory(row)"
                  >
                    编辑
                  </div>
                  <el-popconfirm
                    title="确定删除该分类?"
                    @confirm="deleteCategory(row)"
                  >
                    <template #reference>
                      <div
                        class="option"
                        style="flex: 1; text-align: center; cursor: pointer"
                      >
                        删除
                      </div>
                    </template>
                  </el-popconfirm>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页器 -->
          <el-pagination
            v-model:current-page="current"
            v-model:page-size="pageSize"
            :page-sizes="[1, 5, 10, 20]"
            :background="true"
            layout="prev, pager, next, jumper,->,sizes,total"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </el-card>
      </el-col>
      <el-col :span="10">
        <el-card class="category-data-card">
          <template #header>
            <div class="category-header">
              <div class="title">二级分类</div>
              <div class="add-category" @click="addChildCategory">
                新增二级分类
              </div>
            </div>
          </template>
          <el-table
            style="margin-bottom: 20px"
            ref="singleTableRef"
            :data="childArr"
          >
            <el-table-column
              type="index"
              header-align="left"
              align="left"
              width="100"
              label="序号"
            >
              <template #default="scope">
                <span>{{ (current - 1) * pageSize + scope.$index + 1 }}</span>
              </template>
            </el-table-column>

            <el-table-column
              align="left"
              label="分类名称"
              prop="name"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              align="center"
              label="操作"
              width="200px"
              style="display: flex; justify-content: center"
            >
              <template v-slot="{ row }" style="display: flex; gap: 10px">
                <div class="cell" style="display: flex">
                  <div
                    class="option"
                    style="
                      flex: 1;
                      text-align: center;
                      cursor: pointer;
                      margin-right: 5px;
                    "
                    @click="editCategory(row)"
                  >
                    编辑
                  </div>
                  <el-popconfirm
                    title="确定删除该分类?"
                    @confirm="deleteCategory(row)"
                  >
                    <template #reference>
                      <div
                        class="option"
                        style="flex: 1; text-align: center; cursor: pointer"
                      >
                        删除
                      </div>
                    </template>
                  </el-popconfirm>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <el-dialog
    v-model="dialogFormVisible"
    :title="form.id ? '修改分类' : '新增分类'"
    width="400px"
  >
    <el-form label-width="70px">
      <el-form-item label="分类名称">
        <el-input placeholder="请输入分类名称" v-model="form.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  reqAdd,
  reqDelete,
  reqGetChildCategoryById,
  reqList,
  reqUpdate,
} from '@/api/mis/category'
import { ElMessage } from 'element-plus'
import type { Category } from '@/api/mis/category/type'

let current = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(10)

// 存储获取到的已有的信息
let parentArr = ref<Category[]>()
let childArr = ref<Category[]>()

//控制对话框
let dialogFormVisible = ref<boolean>(false)

const formLabelWidth = '80px'
//用于新增或修改菜单所用的表单
const form = reactive({
  name: '',
  parentCategoryId: 0,
  id: 0,
})

let selectedCategoryArr = ref([])
const currentRow = ref()

// 挂载完成之后获取所有留言信息
onMounted(() => {
  getAllCategory()
})
// 获取所有用户信息的方法
const getAllCategory = async () => {
  const params = {
    current: current.value,
    pageSize: pageSize.value,
  }
  const result = await reqList(params)
  if (result.code === '0') {
    parentArr.value = result.data.records
    total.value = result.data.total ?? 0 // 如果 total 是 undefined，则使用 0 作为默认值
  }
}
// 当前页改变时的回调
const handleCurrentChange = () => {
  getAllCategory()
}

const addChildCategory = () => {
  if (currentRow.value && currentRow.value.id) {
    Object.assign(form, { name: '', id: 0, parentCategoryId: 0 })
    Object.assign(form, { parentCategoryId: currentRow.value.id })
    dialogFormVisible.value = true
  } else {
    ElMessage.error('请先选择一级分类')
  }
}
const handleCategoryCurrentChange = (row: any) => {
  currentRow.value = row
  if (row) {
    getChildCategory(row.id)
  }
}
const editCategory = (row: any) => {
  dialogFormVisible.value = true
  console.log(row)
  //将row对象中的树形复制到form中
  Object.assign(form, row)
}
const getChildCategory = async (parentCategoryId: number) => {
  const result = await reqGetChildCategoryById(parentCategoryId)
  if (result.code === '0') {
    childArr.value = result.data
  }
}
const handleSizeChange = () => {
  current.value = 1
  getAllCategory()
}

const deleteCategory = async (row: any) => {
  const params = {
    id: row.id,
  }
  const result = await reqDelete(params)
  if (result.code == '0') {
    ElMessage({ type: 'success', message: '删除成功！' })
    await getChildCategory(currentRow.value.id)
    await getAllCategory()
  } else {
    ElMessage({ type: 'error', message: '删除失败！' })
  }
}
const edit = async (row: any) => {
  //将row对象中的树形复制到form中
  Object.assign(form, row)
}

const openDialog = () => {
  dialogFormVisible.value = true
  // 清空数据
  Object.assign(form, { name: '' })
}

// 保存按钮的回调
const save = async () => {
  let result: any
  if (form.id == 0) {
    result = await reqAdd(form)
  } else {
    result = await reqUpdate(form)
  }
  if (result.code == 0) {
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: form.id ? ' 修改成功' : '添加成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: result.message,
    })
  }
  console.log(form)
  if (form.parentCategoryId != null && form.parentCategoryId != 0) {
    await getChildCategory(form.parentCategoryId)
  }
  await getAllCategory()
}

// 表单项被改变选中状态时会触发的回调
const selectedChange = (value: any) => {
  selectedCategoryArr.value = value
}

// 每页数据条数变化时的回调
</script>

<style scoped lang="scss">
.category-data-card {
  .category-header {
    display: flex;
    justify-content: space-between;

    .add-category {
      cursor: pointer;
      color: #007fff;
    }
  }
}

.option {
  color: #007fff;
}
</style>
